package org.xiaodongwei.jvm.op;

import org.xiaodongwei.jvm.exe.JVMStack;
import org.xiaodongwei.jvm.utils.ObjectUtils;
import tech.medivh.classpy.classfile.bytecode.Branch;
import tech.medivh.classpy.classfile.bytecode.Instruction;
import tech.medivh.classpy.classfile.constant.ConstantPool;
import tech.medivh.classpy.classfile.jvm.Opcode;

public class IfleOpCodeExecute extends OpCodeExecute {

    public IfleOpCodeExecute(JVMStack jvmStack, ConstantPool constantPool) {
        this.opCode = Opcode.ifle;
        this.jvmStack = jvmStack;
        this.constantPool = constantPool;
    }

    @Override
    public void execute(Instruction instruction) {
        // 获取当前的比较码，根据比较码来进行分支跳转
        Object compareCode = jvmStack.peek().getOperateStack().pop();
        if (ObjectUtils.isSafeCompareCode(compareCode)) {
            int code = ObjectUtils.toInteger(compareCode);
            Branch branch = (Branch) instruction;
            // 获取跳转的分支索引值，然后跳转到对应的分支
            int jumpTo = branch.getJumpTo();
            jvmStack.peek().jumpTo(jumpTo);
        }
    }
}
